package com.gzw.dms.activity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.gzw.dms.BuildConfig;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.BaseSpinnerAdapter;
import com.gzw.dms.bean.BackOrderInfo;
import com.gzw.dms.bean.ShippingOrderInfo;
import com.gzw.dms.bean.SingnInfo;
import com.gzw.dms.bean.SpinnerInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.DateUtil;
import com.gzw.dms.utils.FileUtil;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.L;
import com.gzw.dms.utils.ScreenUtils;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.ToolFor9Ge;
import com.gzw.dms.utils.UrlUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StorageUtils;

public class BackOrderScanActivity extends BaseActivity {
    private Button btn_sign;
    private String ddid;
    private EditText et_actual_number;
    private EditText  et_sign_user;
    private EditText et_defect_number,et_sign_remarks;
    private EditText et_sign_name,ic_receipt_name2;
    private int imgH = 800;
    private int imgW = 600;
    private ImageView iv_uploading;
    private Context mContext;
    private String newFileName;
    private String isUploadPhotos = "0";
    private  String fileRoot = "singReverseOrder";
    private Spinner sp_sign_result;
    private TextView  tv_shiping_order_num1, tv_shiping_order_num2, tv_shipping_order_state1,
            tv_shipping_order_state2, tv_send_time1, tv_send_time2,tv_scantime,
            tv_goods_name1, tv_goods_name2, tv_goods_num1, tv_goods_num2, tv_goods_weight1,
            tv_goods_weight2, tv_goods_vol1, tv_goods_vol2, tv_sign_user1,tv_sign_user2,  tv_actual_number,
             tv_defect_number,tv_send_station1,tv_send_station2,tv_end_adress1,tv_end_adress2,ic_shiping_order_goid1,ic_shiping_order_goid2,
            tv_custom_name1,tv_custom_name2,tv_custom_contact1,tv_custom_contact2,ic_custom_tel1,ic_custom_tel2,ic_receipt_name1;

    private Intent mIntent;
    private  Intent intent;
    private BackOrderInfo shippingOrder;
    private SingnInfo info;
    private ProgressDialog mProgressDialog;
    private Toolbar toolbar;
    private java.lang.String tag="BackScanActivity---->";
    private String path;
    private int REQUEST_CODE_CAMERA=1;
    private DatePickerDialog dpd;
    private LinearLayout layout_scan;
    private String fileName1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        source();
        initConfig();
        init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_back_order_scan);

    }

    @Override
    public void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        btn_sign = ((Button) findViewById(R.id.btn_sign));
        iv_uploading = ((ImageView) findViewById(R.id.iv_uploading));
        tv_send_station1 = (TextView) findViewById(R.id.ic_send_station).findViewById(R.id.tv_left);
        tv_send_station2 = (TextView) findViewById(R.id.ic_send_station).findViewById(R.id.tv_right);
        tv_end_adress1 = (TextView) findViewById(R.id.ic_end_address).findViewById(R.id.tv_left);
        tv_end_adress2 = (TextView) findViewById(R.id.ic_end_address).findViewById(R.id.tv_right);
        sp_sign_result = ((Spinner) findViewById(R.id.sp_sign_result));

        ic_shiping_order_goid1 = (TextView) findViewById(R.id.ic_shiping_order_goid).findViewById(R.id.tv_left);
        ic_shiping_order_goid2 = (TextView) findViewById(R.id.ic_shiping_order_goid).findViewById(R.id.tv_right);
        tv_shiping_order_num1 = (TextView) findViewById(R.id.ic_shiping_order_num).findViewById(R.id.tv_left);
        tv_shiping_order_num2 = (TextView) findViewById(R.id.ic_shiping_order_num).findViewById(R.id.tv_right);
        tv_shipping_order_state1 = (TextView) findViewById(R.id.ic_shipping_order_state).findViewById(R.id.tv_left);
        tv_shipping_order_state2 = (TextView) findViewById(R.id.ic_shipping_order_state).findViewById(R.id.tv_right);
        tv_send_time1 = (TextView) findViewById(R.id.ic_send_time).findViewById(R.id.tv_left);
        tv_send_time2 = (TextView) findViewById(R.id.ic_send_time).findViewById(R.id.tv_right);
        tv_custom_name1 = (TextView) findViewById(R.id.ic_custom_name).findViewById(R.id.tv_left);
        tv_custom_name2 = (TextView) findViewById(R.id.ic_custom_name).findViewById(R.id.tv_right);
        tv_custom_contact1 = (TextView) findViewById(R.id.ic_custom_contact).findViewById(R.id.tv_left);
        tv_custom_contact2 = (TextView) findViewById(R.id.ic_custom_contact).findViewById(R.id.tv_right);
        ic_custom_tel1 = (TextView) findViewById(R.id.ic_custom_tel).findViewById(R.id.tv_left);
        ic_custom_tel2 = (TextView) findViewById(R.id.ic_custom_tel).findViewById(R.id.tv_right);

        tv_goods_name1 = (TextView) findViewById(R.id.ic_goods_name).findViewById(R.id.tv_left);
        tv_goods_name2 = (TextView) findViewById(R.id.ic_goods_name).findViewById(R.id.tv_right);
        tv_goods_num1 = (TextView) findViewById(R.id.ic_goods_num).findViewById(R.id.tv_left);
        tv_goods_num2 = (TextView) findViewById(R.id.ic_goods_num).findViewById(R.id.tv_right);
        tv_goods_weight1 = (TextView) findViewById(R.id.ic_goods_weight).findViewById(R.id.tv_left);
        tv_goods_weight2 = (TextView) findViewById(R.id.ic_goods_weight).findViewById(R.id.tv_right);
        tv_goods_vol1 = (TextView) findViewById(R.id.ic_goods_vol).findViewById(R.id.tv_left);
        tv_goods_vol2 = (TextView) findViewById(R.id.ic_goods_vol).findViewById(R.id.tv_right);


        tv_sign_user1 = (TextView) findViewById(R.id.ic_sign_user).findViewById(R.id.tv_left);
        tv_sign_user2 = (TextView) findViewById(R.id.ic_sign_user).findViewById(R.id.tv_left);

        tv_actual_number = (TextView) findViewById(R.id.ic_actual_number).findViewById(R.id.tv_left);
        tv_defect_number = (TextView) findViewById(R.id.ic_defect_number).findViewById(R.id.tv_left);
        ic_receipt_name1 = (TextView) findViewById(R.id.ic_receipt_name).findViewById(R.id.tv_left);

        et_actual_number = (EditText) findViewById(R.id.ic_actual_number).findViewById(R.id.et_right);
        et_defect_number = (EditText) findViewById(R.id.ic_defect_number).findViewById(R.id.et_right);
        et_sign_user = (EditText) findViewById(R.id.ic_sign_user).findViewById(R.id.et_right);
        ic_receipt_name2 = (EditText) findViewById(R.id.ic_receipt_name).findViewById(R.id.et_right);
        et_sign_remarks = (EditText) findViewById(R.id.et_sign_remarks);
//        tv_scantime = (TextView) findViewById(R.id.tv_sign_time);

        layout_scan = (LinearLayout) findViewById(R.id.layout_scan);
        layout_scan.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("运单签收");
        setSupportActionBar(toolbar);
        ArrayList ls = new ArrayList();
        ls.add(new SpinnerInfo("1", "正常签收"));
        ls.add(new SpinnerInfo("0", "异常签收"));

        ic_receipt_name1.setText("*收货客户:");
        tv_shiping_order_num1.setText("货运编号:");
        ic_shiping_order_goid1.setText("出货订单号:");
        tv_shipping_order_state1.setText("运单状态:");
        tv_send_station1.setText("起运地:");
        tv_end_adress1.setText("终到位置");
        tv_send_time1.setText("起运时间:");
        tv_goods_name1.setText("货物名称:");
        tv_goods_num1.setText("总件数:");
        tv_goods_weight1.setText("总重量:");
        tv_goods_vol1.setText("总体积:");
        tv_sign_user1.setText("*收货经办:");
        tv_custom_name1.setText("发货客户名称:");
        tv_custom_contact1.setText("发货客户联系人:");
        ic_custom_tel1.setText("发货客户电话:");
        tv_actual_number.setText("*实际数量:");
        tv_defect_number.setText("*缺失数量:");

        BaseSpinnerAdapter Adapter = new BaseSpinnerAdapter(mContext, ls);
        sp_sign_result.setAdapter(Adapter);
        mIntent = getIntent();
        shippingOrder = (BackOrderInfo) mIntent.getExtras().get(
                "shippingOrder");
        et_actual_number.setInputType(InputType.TYPE_CLASS_NUMBER);
        et_defect_number.setInputType(InputType.TYPE_CLASS_NUMBER);

    }

    @Override
    public void initEvents() {
        btn_sign.setOnClickListener(new myOnClick());
//        tv_scantime.setOnClickListener(new myOnClick());
        iv_uploading.setOnClickListener(new myOnClick());
        toolbar.setNavigationOnClickListener(new myOnClick());
    }

    public void source() {
        iv_uploading.getLayoutParams().height = (ScreenUtils
                .getScreenWidth(mContext) / 3);
        iv_uploading.getLayoutParams().width = (ScreenUtils
                .getScreenWidth(mContext) / 3);
//        et_sign_user.setText(shippingOrder.getReceipt_name());
        tv_shiping_order_num2.setText(shippingOrder.getShiping_order_num());
        ic_shiping_order_goid2.setText(shippingOrder.getShiping_order_goid());

        Integer state = shippingOrder.getShipping_order_state();
        if (state == 0) {
            tv_shipping_order_state2.setText("未签收");
        } else if (state == 1) {
            tv_shipping_order_state2.setText("分配运单");
        } else if (state == 2) {
            tv_shipping_order_state2.setText("司机提货");
        } else if (state == 3) {
            tv_shipping_order_state2.setText("电子围栏签收");
        }else if (state == 4) {
            tv_shipping_order_state2.setText("实际签收");
        }
        tv_custom_name2.setText(shippingOrder.getCustom_name());
        tv_custom_contact2.setText(shippingOrder.getCustom_contact());
        ic_custom_tel2.setText(shippingOrder.getCustom_tel());
        tv_end_adress2.setText(shippingOrder.getEnd_mechanism());
        tv_send_station2.setText(shippingOrder.getSend_station());
        tv_send_time2.setText(shippingOrder.getSend_time());
        tv_goods_name2.setText(shippingOrder.getGoods_name());
        tv_goods_num2.setText(String.valueOf(shippingOrder.getGoods_num()));
        tv_goods_weight2.setText(shippingOrder.getGoods_weight());
        tv_goods_vol2.setText(shippingOrder.getGoods_vol());
        ddid = shippingOrder.getShiping_order_id();
        ic_receipt_name2.setText(shippingOrder.getEnd_mechanism());
        et_actual_number.setText(shippingOrder.getGoods_num().toString());
        et_defect_number.setText("0");
    }



    /**
     * 检验是否有SD卡
     * @true or false
     */
    public static boolean isHaveSDCard() {
        Boolean isExist = Environment
                .getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        return isExist;
    }

    public void SaveHttpClientPost() {

        if (isNull(et_actual_number)) {
            T.showShort(mContext, "实际数量不能为空");
            return;
        }
        if (isNull(et_defect_number)) {
            T.showShort(mContext, "缺失数量不能为空");
            return;
        }

//        isUploadPhotos = FileUtil.getInstance().isUpload();
//        if (isUploadPhotos=="0") {
//            T.showShort(mContext, "请上传图片");
//            return;
//        }else if(isUploadPhotos=="1"){
//            T.showShort(mContext, "请等待图片上传");
//            return;
//        }

        if (info == null)
            info = new SingnInfo();
        info.setOrder_id(ddid);
        info.setOrder_number(tv_shiping_order_num2.getText().toString().trim());
        info.setSign_user(et_sign_user.getText().toString().trim());
        SpinnerInfo spinnerInfo=(SpinnerInfo)sp_sign_result.getSelectedItem();
        int result = Integer.valueOf(spinnerInfo.getId());
        info.setSign_result(result);
        info.setActual_number(Integer.parseInt(et_actual_number.getText()
                .toString()));
        info.setDefect_number(Integer.parseInt(et_defect_number.getText()
                .toString()));
//        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//        String date=sdf.format(new java.util.Date());
//        info.setSign_time(date);
        info.setSign_user(ic_receipt_name2.getText().toString().trim());
        info.setLat(MyApplication.getLat());
        info.setLng(MyApplication.getLng());
        info.setSign_remarks(et_sign_remarks.getText().toString().trim());
        SignShipOrder signShipOrder = new SignShipOrder();
        signShipOrder.execute(info);
    }

    public class SignShipOrder extends AsyncTask<SingnInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);

        }

        protected String doInBackground(SingnInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("sign_order", params[0]);
            map.put("newFileName", fileName1);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appSignReverseOrder"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sign:
                    SaveHttpClientPost();
                    break;
                case R.id.iv_uploading:
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            path = resultList.get(0).getPhotoPath().toString();
                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .showImageOnFail(R.drawable.ic_gf_default_photo)
                                    .showImageForEmptyUri(R.drawable.ic_gf_default_photo)
                                    .showImageOnLoading(R.drawable.ic_gf_default_photo).build();
                            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file:/" + path, iv_uploading, options);

                            if (!isNull(path)) {
                                fileName1 = shippingOrder.getShiping_order_num().trim() + "--" + DateUtil.getFileName();
                                uploadPhotos(path, fileName1);

                            }
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            T.showShort(getApplicationContext(), errorMsg);
                            Log.e("onHanlderFailure", "");
                        }
                    });
                    break;

//                case R.id.tv_sign_time:
//                    Calendar mCalendar = Calendar.getInstance(Locale.CHINA);
//                    int year = mCalendar.get(Calendar.YEAR);
//                    int month = mCalendar.get(Calendar.MONTH);
//                    int day = mCalendar.get(Calendar.DAY_OF_MONTH);
//
//                    dpd = new DatePickerDialog(mContext, new Datelistener(), year, month,
//                            day);
//                    dpd.show();
//                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    class Datelistener implements DatePickerDialog.OnDateSetListener {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            tv_scantime.setText(year + "-" + (monthOfYear + 1) + "-"
                    + dayOfMonth);
        }
    }
    private void uploadPhotos(String path, String fileName){

        Bitmap bitmap = null;
        File file = new File(path);
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                bitmap = BitmapFactory.decodeStream(fis);
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (bitmap!=null) {
//                newFileName = shippingOrder.getShiping_order_num()+"--"+DateUtil.getFileName();
                bitmap = ToolFor9Ge.zoomImg(bitmap, imgW, imgH);
                FileUtil.getInstance().uploadFile(bitmap, fileName,fileRoot);
            }
            if(bitmap.isRecycled()==false) //如果没有回收
                bitmap.recycle();
        }
    }

    private void initConfig() {
        //配置主题
        //ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder()

                .build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(false)
                .build();

        //配置imageloader
        ImageLoader imageloader = new UILImageLoader();
        //设置核心配置信息
        CoreConfig coreConfig = new CoreConfig.Builder(getApplicationContext(), imageloader, theme)
                .setDebug(BuildConfig.DEBUG)
                .setFunctionConfig(functionConfig)

                .build();
        GalleryFinal.init(coreConfig);
    }

    private void init() {
        File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3) // default
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(tag, "onStart called.");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(tag, "onRestart called.");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(tag, "onResume called.");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(tag, "onPause called.");
    }

    @Override
    protected void onStop() {
        L.i(tag, "onStop()");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        L.i(tag, "onDestroy()");
        Intent sevice = new Intent(this, ScanActivity.class);
        this.startService(sevice);
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("filePath", path);
//        Log.d(TAG, "onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (TextUtils.isEmpty(path)) {
            path = savedInstanceState.getString("filePath");
        }
    }
}